<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;

//场租合同表
class XcRenterContract extends Model
{
    protected $table = 'xc_renter_contract';
    protected $guarded = ['id'];

    /**
     * 计算场租方分润金额，需要取合同表分润数据
     *
     */
    public function GetRenterProfit($money, $renter_id)
    {
        $renter_profit = 0;
        $fr = $this->where([["renter_id", '=', $renter_id], ['starttime', '<=', date("Y-m-d")], ['endtime', '>=', date("Y-m-d")]])->orderBy("id", "desc")->get()->toArray();

        if (!empty($fr)) {
            if ($fr[0]['operation_type'] == 1) {
                $renter_profit = round($money * $fr[0]['operation_price2'] / 10, 2);
            } else if ($fr[0]['operation_type'] == 2) {
                $renter_profit = round($fr[0]['operation_price1'], 2);
            }
        }

        return $renter_profit;
    }

    /**
     * 场租在某一年 所有合同的 所有有效月份
     *
     */
    public function ymMonths($renter_id, $year = 0)
    {
        $year = $year ?: date('Y');
        $date_beg = $year . '-01-01';
        $date_end = $year . '-12-31';
        $contract = XcRenterContract::query()->where('renter_id', $renter_id)->where('endtime', '>=', $date_beg)->orderBy('id', 'asc')->get()->toArray();
        if (!$contract) {
            return [];
        }
        $data = [];
        foreach ($contract as $val) {
            if ($val['starttime'] > $date_end) break;
            if ($val['starttime'] >= $date_beg) {
                $beg_month = (int)substr($val['starttime'], 5, 2);
            } else {
                $beg_month = 1;
            }

            if ($val['endtime'] >= $date_end) {
                $end_month = 12;
            } else {
                $end_month = (int)substr($val['endtime'], 5, 2);
            }

            for ($i = $beg_month; $i <= $end_month; $i++) {
                $data[] = $i > 9 ? $i : '0' . $i;
            }
        }
        return $data;
    }

    /**
     * 场租在某一年 某个合同的 有效月份
     * $y : 2024
     */
    public function yMonths(object $contract, $y = 0)
    {
        $starttime_year = (int)$contract->starttime;
        $endtime_year = (int)$contract->endtime;
        if ($y) {
            $year = $y;
            if ($endtime_year < $year || $starttime_year > $year) {
                return ['year' => $y ?: $starttime_year, 'months' => []];
            }
        } else {
            $year = date('Y');
            if ($endtime_year < $year || $starttime_year > $year) {
                $year = $starttime_year;
            }
        }

        if ($endtime_year >= $year) {
            $end_month = $endtime_year == $year ? (int)substr($contract->endtime, 5, 2) : 12;
            $beg_month = $starttime_year == $year ? (int)substr($contract->starttime, 5, 2) : 1;
        } else {
            $end_month = $starttime_year == $endtime_year ? (int)substr($contract->endtime, 5, 2) : 12;
            $beg_month = (int)substr($contract->starttime, 5, 2);
        }
        for ($i = $beg_month; $i <= $end_month; $i++) {
            $months[] = $i > 9 ? $i : '0' . $i;
        }
        return ['year' => $year, 'months' => $months];
    }

    /**
     * 获取时间覆盖的合同
     * @param $start_time
     * @param $end_time
     * @return array
     */
    public function getCoverContact($start_time, $end_time)
    {
        $list = $this->whereRaw("((starttime >= '{$start_time}' AND starttime < '{$end_time}') 
OR (starttime <= '{$start_time}' AND  endtime >= '{$end_time}') 
OR (endtime > '{$start_time}' AND endtime <= '{$end_time}') 
OR (starttime <= '{$start_time}' AND  endtime >= '{$end_time}'))")
            ->selectRaw("*,  DATE_FORMAT(starttime, '%Y-%m') as starttime, DATE_FORMAT(endtime, '%Y-%m') as endtime")->orderBy('id', 'desc')->get()->toArray();

        $data = [];
        foreach ($list as $value) {
            $data[$value['renter_id']][] = $value;
        }

        return $data;
    }

    /**
     * 获取时间覆盖的合同
     * @param $date
     * @return array
     */
    public function getContactByDate($date)
    {
        $list = $this->whereRaw("starttime <= '{$date}' AND endtime > '{$date}'")
            ->selectRaw("*")->orderBy('id', 'desc')->get()->toArray();

        $data = [];
        foreach ($list as $value) {
            $data[$value['renter_id']] = $value;
        }

        return $data;
    }

    /**
     * 获取时间覆盖的合同
     * @param $year
     * @return array
     */
    public function getContactByYear($year)
    {
        $list = $this->whereRaw("YEAR(starttime) <= {$year} AND YEAR(endtime) >= {$year} ")
            ->selectRaw("*")->orderBy('id', 'desc')->get()->toArray();

        $data = [];
        foreach ($list as $value) {
            $data[$value['renter_id']][] = $value;
        }

        return $data;
    }
}
